import sys
from os.path import abspath, join, dirname
import random
from pymongo import MongoClient
from time import sleep

from app.core.random_str import getRandomStr

ROOT_DIR = abspath(join(dirname(abspath(__file__)), '../../'))
if ROOT_DIR not in sys.path:
    sys.path.append(ROOT_DIR)
import datetime
import json
from app.settings.config import MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DB, MYSQL_PORT

from app.service.format_datetime import format_datetime, format_datetime_group
from app.service.comment import media_root_comments, get_comment_object_first_comment
from app.service.menu import new_menu
from app.service.search import init_all_mapping, index_my_media, search_my_media
from main import app

from app.db.search import es_init, es

from app.lib.txt import path_str_arr
from app.model import mysql
from app.service.folder import new_folder, get_folders, get_user_root_folder_ids, reset_folder_covers, \
    reset_folder_and_parent_covers
from tortoise import Tortoise, run_async
from app.model.mysql import Folder
from tortoise.query_utils import Q


def phoneNORandomGenerator():
    prelist = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "147", "150", "151", "152", "153",
               "155", "156", "157", "158", "159", "186", "187", "188"]
    return random.choice(prelist) + "".join(random.choice("0123456789") for i in range(8))


async def run():
    """"""
    await Tortoise.init(db_url=f'mysql://dci:FfRyn2b5BKM3MNPz@218.244.143.31:3317/designer',
                        modules={"models": ["app.model.mysql"]})
    await Tortoise.generate_schemas()
    # while True:
    #     if await mysql.User.all().count() > 99:
    #         break
    #     sleep(0.1)
    #     print(await mysql.User.all().count())
    #     try:
    #         await mysql.User.create(mobile=phoneNORandomGenerator(), nickname=f"新用户{getRandomStr(6)}")
    #         await mysql.UserInfo.create(interest_tags=[2, 4, 6])
    #     except:
    #         try:
    #             await mysql.User.create(mobile=phoneNORandomGenerator(), nickname=f"新用户{getRandomStr(7)}")
    #             await mysql.UserInfo.create(interest_tags=[2, 4, 6])
    #         except Exception as e:
    #             print(e)
    # user = await mysql.User.all()
    # for i in user:
    #     for j in range(10):
    #         try:
    #             await mysql.Follow.create(user_id=i.id, follow_user_id=random.randint(0, 100))
    #         except Exception as e:
    #             print(e)

    # conn = MongoClient("192.168.0.166", 47017)
    # db = conn.dome
    # myset = db.opus
    # master = await mysql.User.filter(mobile="18301365447", nickname="苗雨露").first()
    # if not master:
    #     master = await mysql.User.create(mobile="18301365447", nickname="苗雨露")
    #     await mysql.UserInfo.create(interest_tags=[2, 4, 6], is_master=True)
    # for item in myset.find()[:3]:
    #     for key, value in item["channel_covers"].items():
    #         try:
    #             photo = await mysql.Photo.create(system_tags=json.dumps(["客厅", "欧式"], ensure_ascii=False),
    #                                              text=value["desc"] if value["desc"] else " ",
    #                                              key=value["exif"]["key"],
    #                                              width=value["exif"]["width"],
    #                                              file_exif=json.dumps(value["exif"], ensure_ascii=False),
    #                                              height=value["exif"]["width"],
    #                                              file_size=value["exif"]["size"],
    #                                              space=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                              style=json.dumps(["国风", "英伦"], ensure_ascii=False),
    #                                              house_type=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                              color_values=value["exif"]["color"],
    #                                              )
    #             media = await mysql.Media.create(object_type=1, object_id=photo.id, user_id=master.id)
    #         # print(value["desc"])
    #         except:
    #             pass
    #
    # for item in myset.find()[5:10]:
    #     print(item)
    #     try:
    #         case = await mysql.Case.create(kind=1,
    #                                        system_tags=json.dumps(["客厅", "欧式"], ensure_ascii=False),
    #                                        title=item["title"],
    #                                        text=item["title"],
    #                                        style=json.dumps(["国风", "英伦"], ensure_ascii=False),
    #                                        house_type=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                        cover="photo/5bea9270eb6c257d7b99df16/a5156425a555d5b123f0168969d16c9be9a86403"
    #                                        )
    #         parent_media = await mysql.Media.create(object_type=2, object_id=case.id, user_id=master.id)
    #         for key, value in item["channel_covers"].items():
    #             photo = await mysql.Photo.create(system_tags=json.dumps(["客厅", "欧式"], ensure_ascii=False),
    #                                              text=value["desc"] if value["desc"] else " ",
    #                                              key=value["exif"]["key"],
    #                                              width=value["exif"]["width"],
    #                                              file_exif=json.dumps(value["exif"], ensure_ascii=False),
    #                                              height=value["exif"]["width"],
    #                                              file_size=value["exif"]["size"],
    #                                              space=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                              style=json.dumps(["国风", "英伦"], ensure_ascii=False),
    #                                              house_type=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                              color_values=value["exif"]["color"],
    #                                              )
    #             media = await mysql.Media.create(object_type=1, object_id=photo.id, user_id=master.id, parent_id=parent_media.id)
    #         # print(value["desc"])
    #     except:
    #         pass
    # for item in myset.find()[11:16]:
    #     print(item)
    #     try:
    #         case = await mysql.Case.create(kind=2,
    #                                        system_tags=json.dumps(["客厅", "欧式"], ensure_ascii=False),
    #                                        title=item["title"],
    #                                        text=item["title"],
    #                                        style=json.dumps(["国风", "英伦"], ensure_ascii=False),
    #                                        house_type=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                        cover="photo/5bea9270eb6c257d7b99df16/a5156425a555d5b123f0168969d16c9be9a86403"
    #                                        )
    #         parent_media = await mysql.Media.create(object_type=2, object_id=case.id, user_id=master.id)
    #         for key, value in item["channel_covers"].items():
    #             photo = await mysql.Photo.create(system_tags=json.dumps(["客厅", "欧式"], ensure_ascii=False),
    #                                              text=value["desc"] if value["desc"] else " ",
    #                                              key=value["exif"]["key"],
    #                                              width=value["exif"]["width"],
    #                                              file_exif=json.dumps(value["exif"], ensure_ascii=False),
    #                                              height=value["exif"]["width"],
    #                                              file_size=value["exif"]["size"],
    #                                              space=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                              style=json.dumps(["国风", "英伦"], ensure_ascii=False),
    #                                              house_type=json.dumps(["一居", "二居", "复式"], ensure_ascii=False),
    #                                              color_values=value["exif"]["color"],
    #                                              )
    #             media = await mysql.Media.create(object_type=1, object_id=photo.id, user_id=master.id, parent_id=parent_media.id)
    #         # print(value["desc"])
    #     except:
    #         pass
    # video = {
    #     "_id": "5beacca1eb6c25025f520c2e",
    #     "desc": "专注",
    #     "medias":
    #         {
    #             "type": "3",
    #             "key": "video/5bea9270eb6c257d7b99df1d/b7135fea4011ec9b6b24a131c22aeb8cb8453b49",
    #             "cover_key": "video/5bea9270eb6c257d7b99df1d/e68e60c24dc0a23fc92b4dd9312f1b7994edc58b",
    #             "crop": "",
    #             "exif": {
    #                 "size": "2156046",
    #                 "format": "video/mp4",
    #                 "width": "1088",
    #                 "height": "816",
    #                 "colorModel": "",
    #                 "orientation": "",
    #                 "duration": "3"
    #             }
    #         }
    # }
    # obj = await mysql.Video.create(system_tags=json.dumps(["客厅", "欧式"], ensure_ascii=False),
    #                          text=video["desc"],
    #                          key=video["medias"]["key"],
    #                          width=video["medias"]["exif"]["width"],
    #                          height=video["medias"]["exif"]["height"],
    #                          duration=video["medias"]["exif"]["duration"],
    #                          file_size=video["medias"]["exif"]["size"],
    #                          file_exif=json.dumps(video["medias"]["exif"], ensure_ascii=False)
    #                          )
    # await mysql.Media.create(object_type=4, object_id=obj.id, user_id=master.id)

    es_init()




async def close_run():
    """"""
    await Tortoise.close_connections()



async def main():
    """"""
    await run()
    await init_all_mapping()

    await close_run()


if __name__ == "__main__":
    run_async(main())
    pass
